package com.cg.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cg.business.CGUserController;
import com.cg.client.Rides;
import com.cg.util.CGUtilClass;

public class CompareCommute extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	
	private static Log log = LogFactory.getLog(GetCGUsers.class.getName());
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		log.info("Inside CompareCommute servlet");
		HttpSession session = request.getSession(true);
		String startTime = null;
		String endTime = null;
		int startRadius = 0;
		int endRadius = 0;
		String startLat = null;
		String startLng = null;
		String endLat = null;
		String endLng = null;
		String checkBoxTransportModes = null;
		if(request.getParameter("startDate")!= null && request.getParameter("endDate")!= null 
		  && request.getParameter("startRadius")!= null&& request.getParameter("endRadius")!= null 
		  && request.getParameter("checkBoxVal")!=null
		  && request.getParameter("slat")!=null && request.getParameter("slng")!=null
		  && request.getParameter("elat")!=null && request.getParameter("elng")!=null
		 )
		{
	
					
					startLat = request.getParameter("slat");
					startLng = request.getParameter("slng");
					endLat = request.getParameter("elat");
					endLng = request.getParameter("elng");
					startTime = request.getParameter("startDate").toString();
					endTime = request.getParameter("endDate").toString();
					checkBoxTransportModes = request.getParameter("checkBoxVal").toString();
					startRadius= Integer.parseInt(request.getParameter("startRadius").toString())*1000;
					endRadius= Integer.parseInt(request.getParameter("endRadius").toString())*1000;
					
					log.debug("Comapare Start Lat: "+ startLat + "  " +
							  "Comapare Start Lng: "+ startLng + "  " +
							  "Comapare End Lat: "+ endLat + "  " +
							  "Comapare End Lng: " + endLng + "  " +
							  "Comapare Start Radius: "+ startRadius + "  " +
							  "Comapare End Radius: "+ endRadius + "  " +
							  "Comapare Start Date: "+ startTime + "  " +
							  "Comapare End Date: "+ endTime + "  " +
							  "Comapare Transport: "+ checkBoxTransportModes); 
		}
			
				String[] temp = null;
				if(checkBoxTransportModes!=null){
					String str = checkBoxTransportModes;
					/* delimiter */
					String delimiter = " ";
					/* given string will be split by the argument delimiter provided. */
					temp = str.split(delimiter);
					temp[0] = temp[0].substring(4);
					/* print substrings */
					for(int i =0; i < temp.length ; i++)
						
						log.debug("Transport Modes: "+temp[i]);
					
				}
				if(startLat!=null && startLng!=null
						&& endLat!=null && endLng!=null
						&& startRadius!= 0 && endRadius != 0  
						&& request.getParameter("startDate")!= null && request.getParameter("endDate")!= null 
						&& request.getParameter("checkBoxVal")!=null && session.getAttribute("startLat")!=null && session.getAttribute("startLng")!= null&&
						session.getAttribute("endLat")!=null&& session.getAttribute("endLng")!=null && session.getAttribute("startRadius")!=null&&
						session.getAttribute("endRadius")!=null && session.getAttribute("startTime")!=null && session.getAttribute("endTime")!= null){
				
				try {
					
					String startLatPrevious = session.getAttribute("startLat").toString();
				    String startLngPrevious = session.getAttribute("startLng").toString();
					String endLatPrevious = session.getAttribute("endLat").toString();
					String endLngPrevious = session.getAttribute("endLng").toString();
	
					int startRadiusPrevious = Integer.parseInt(session.getAttribute("startRadius").toString());
					int endRadiusPrevious = Integer.parseInt(session.getAttribute("endRadius").toString());
					String startTimePrevious = session.getAttribute("startTime").toString();
					String endTimePrevious = session.getAttribute("endTime").toString();
					
					
					
					
					String checkBoxPreviousTransportModes = session.getAttribute("checkBoxTransportModes").toString();
					
					String[] tempPrevious = null;
					if(checkBoxPreviousTransportModes!=null){
						String str = checkBoxPreviousTransportModes;
						/* delimiter */
						String delimiter = " ";
						/* given string will be split by the argument delimiter provided. */
						tempPrevious = str.split(delimiter);
						tempPrevious[0] = tempPrevious[0].substring(4);
						/* print substrings */
						for(int i =0; i < tempPrevious.length ; i++)
							
							log.debug("Transport Modes: "+tempPrevious[i]);
						
					}
				
					
					
					CGUserController controller = new CGUserController();
					
					//Called for the new comparison parameters
					List<Rides> respRideList= controller.getMatchingCGJourneys(Double.parseDouble(startLat), Double.parseDouble(startLng), startRadius, Double.parseDouble(endLat), Double.parseDouble(endLng), endRadius , com.cg.util.DataUtil.convertDate(startTime), com.cg.util.DataUtil.convertDate(endTime),temp);
					
					//Called for getting old results
					
					List<Rides> previousJourneyList= controller.getPreviousCGJourneys(Double.parseDouble(startLatPrevious), Double.parseDouble(startLngPrevious), startRadiusPrevious, Double.parseDouble(endLatPrevious), Double.parseDouble(endLngPrevious), endRadiusPrevious , com.cg.util.DataUtil.convertDate(startTimePrevious), com.cg.util.DataUtil.convertDate(endTimePrevious),tempPrevious);
					
					
					ArrayList<String> latLongList = new ArrayList<String>();
					ArrayList<String> latLongDest = new ArrayList<String>();
					ArrayList<String> rideCategoryList = new ArrayList<String>();
					
					//Previous data
					
					
					ArrayList<String> previousrideCatList = new ArrayList<String>();
					
					Rides ride = new Rides();
					String imgUrlCar = null;
					String iconUrlCar = null;
					String imgUrlBus = null;
					String iconUrlBus = null;
					String imgUrlBicycle = null;
					String iconUrlBicycle = null;
					String imgUrlWalking = null;
					String iconUrlWalking = null;
					String imgUrlTrain = null;
					String iconUrlTrain = null;
					String imgUrlFerry = null;
					String iconUrlFerry = null;
					String imgUrlAeroplane = null;
					String iconUrlAeroplane = null;
					
					
					
				
					
					int totalCo2Car = 0;
					int totalCo2Bus = 0;
					int totalCo2Walking = 0;
					int totalCo2Bicycle = 0;
					int totalCo2Train = 0;
					int totalCo2Ferry = 0;
					int totalCo2Aeroplane = 0;
					int totalDistanceCar = 0;
					int totalDistanceBicycle = 0;
					int totalDistanceWalking = 0;
					int totalDistanceBus = 0;
					int totalDistanceFerry = 0;
					int totalDistanceTrain = 0;
					int totalDistanceAeroplane = 0;
					int journeyCount = 0;
					
					
					//Previous co2 and distance
					
					
					
					
					for(int i = 0;i<respRideList.size();i++){
						if(respRideList.get(i).getId()!=null){
							journeyCount++;
						}
					}
					log.info("Total no of journeys in compared set"+journeyCount);
					request.setAttribute("journeyCount", journeyCount);
					
					
					
					
					//Previous journey
					int journeyPreviousCount = 0;
					for(int i = 0;i<previousJourneyList.size();i++){
						if(previousJourneyList.get(i).getId()!=null){
							journeyPreviousCount++;
						}
					}
					log.info("Total no of journeys in previous set"+journeyPreviousCount);
					request.setAttribute("journeyPreviousCount", journeyPreviousCount);
					
					
					
					
					for(int i = 0;i<respRideList.size();i++){
						totalCo2Car = totalCo2Car+respRideList.get(i).getGrammesCO2Car();				
					}			
					for(int i = 0;i<respRideList.size();i++){
						totalCo2Bus = totalCo2Bus+respRideList.get(i).getGrammesCO2Bus();	
					}
					for(int i = 0;i<respRideList.size();i++){
						totalCo2Walking = totalCo2Walking+respRideList.get(i).getGrammesCO2Walking();	
					}
					for(int i = 0;i<respRideList.size();i++){
						totalCo2Bicycle = totalCo2Bicycle+respRideList.get(i).getGrammesCO2Bicycle();	
					}
					for(int i = 0;i<respRideList.size();i++){
						totalCo2Train = totalCo2Train+respRideList.get(i).getGrammesCO2Train();	
					}
					for(int i = 0;i<respRideList.size();i++){
						totalCo2Ferry = totalCo2Ferry+respRideList.get(i).getGrammesCO2Ferry();	
					}
					for(int i = 0;i<respRideList.size();i++){
						totalCo2Aeroplane = totalCo2Aeroplane+respRideList.get(i).getGrammesCO2Aeroplane();	
					}
					
					
				   int totalCo2 = totalCo2Car+totalCo2Bus+totalCo2Walking+totalCo2Bicycle+totalCo2Train+totalCo2Ferry+totalCo2Aeroplane;

				   //Previous co2 count
				   int totalPreviousCo2Car = 0;
					int totalPreviousCo2Bus = 0;
					int totalPreviousCo2Walking = 0;
					int totalPreviousCo2Bicycle = 0;
					int totalPreviousCo2Train = 0;
					int totalPreviousCo2Ferry = 0;
					int totalPreviousCo2Aeroplane = 0;
					
					
					

					for(int i = 0;i<previousJourneyList.size();i++){
						totalPreviousCo2Car = totalPreviousCo2Car+previousJourneyList.get(i).getGrammesCO2Car();				
					}			
					for(int i = 0;i<previousJourneyList.size();i++){
						totalPreviousCo2Bus = totalPreviousCo2Bus+previousJourneyList.get(i).getGrammesCO2Bus();	
					}
					for(int i = 0;i<previousJourneyList.size();i++){
						totalPreviousCo2Walking = totalPreviousCo2Walking+previousJourneyList.get(i).getGrammesCO2Walking();	
					}
					for(int i = 0;i<previousJourneyList.size();i++){
						totalPreviousCo2Bicycle = totalPreviousCo2Bicycle+previousJourneyList.get(i).getGrammesCO2Bicycle();	
					}
					for(int i = 0;i<previousJourneyList.size();i++){
						totalPreviousCo2Train = totalPreviousCo2Train+previousJourneyList.get(i).getGrammesCO2Train();	
					}
					for(int i = 0;i<previousJourneyList.size();i++){
						totalPreviousCo2Ferry = totalPreviousCo2Ferry+previousJourneyList.get(i).getGrammesCO2Ferry();	
					}
					for(int i = 0;i<previousJourneyList.size();i++){
						totalPreviousCo2Aeroplane = totalPreviousCo2Aeroplane+previousJourneyList.get(i).getGrammesCO2Aeroplane();	
					}
					
					
				   int totalCo2Previous = totalPreviousCo2Car+totalPreviousCo2Bus+
						                  totalPreviousCo2Walking+totalPreviousCo2Bicycle+
						                  totalPreviousCo2Train+totalPreviousCo2Ferry+
						                  totalPreviousCo2Aeroplane;

				   
				   
				   
				   for(int i = 0;i<respRideList.size();i++){
					   totalDistanceCar = totalDistanceCar+respRideList.get(i).getDistanceCar();	
					}
				   
				   for(int i = 0;i<respRideList.size();i++){
					   totalDistanceBicycle = totalDistanceBicycle+respRideList.get(i).getDistanceBicycle();	
					}
				   
				   for(int i = 0;i<respRideList.size();i++){
					   totalDistanceBus = totalDistanceBus+respRideList.get(i).getDistanceBus();	
					}
				   for(int i = 0;i<respRideList.size();i++){
					   totalDistanceWalking = totalDistanceWalking+respRideList.get(i).getDistanceWalking();	
					}
				   
				   for(int i = 0;i<respRideList.size();i++){
					   totalDistanceFerry = totalDistanceFerry+respRideList.get(i).getDistanceFerry();	
					}
				   for(int i = 0;i<respRideList.size();i++){
					   totalDistanceTrain = totalDistanceTrain+respRideList.get(i).getDistanceTrain();	
					}
				   for(int i = 0;i<respRideList.size();i++){
					   totalDistanceAeroplane = totalDistanceAeroplane+respRideList.get(i).getDistanceAeroplane();	
					}
					
				   
				   int totalDistance = totalDistanceCar+totalDistanceBicycle+totalDistanceBus+totalDistanceWalking+totalDistanceFerry+totalDistanceTrain+totalDistanceAeroplane;
				   
				   
				   // Getting the segment percentages
				   double bicycleDistPercentage = Math.floor(((double)totalDistanceBicycle/totalDistance)*100);
				   int percentageBicycleKM = (int)bicycleDistPercentage;
				   		   
				   double carDistPercentage = Math.floor(((double)totalDistanceCar/totalDistance)*100);
				   int percentageCarKM = (int)carDistPercentage;
				  
				   double walkingDistPercentage = Math.floor(((double)totalDistanceWalking/totalDistance)*100);
				   int percentageWalkingKM = (int)walkingDistPercentage;
				   
				   double busDistPercentage = Math.floor(((double)totalDistanceBus/totalDistance)*100);
				   int percentageBusKM = (int)busDistPercentage;
				   
				   double ferryDistPercentage = Math.floor(((double)totalDistanceFerry/totalDistance)*100);
				   int percentageFerryKM = (int)ferryDistPercentage;
				   
				   double trainDistPercentage = Math.floor(((double)totalDistanceTrain/totalDistance)*100);
				   int percentageTrainKM = (int)trainDistPercentage;
				   
				   double aeroplaneDistPercentage = Math.floor(((double)totalDistanceAeroplane/totalDistance)*100);
				   int percentageAeroplaneKM = (int)aeroplaneDistPercentage;
				   
				   
				   
				   
				   // Previous distance
				   
				    int totalPreviousDistanceCar = 0;
					int totalPreviousDistanceBicycle = 0;
					int totalPreviousDistanceWalking = 0;
					int totalPreviousDistanceBus = 0;
					int totalPreviousDistanceFerry = 0;
					int totalPreviousDistanceTrain = 0;
					int totalPreviousDistanceAeroplane = 0;
					
					
					  for(int i = 0;i<previousJourneyList.size();i++){
						  totalPreviousDistanceCar = totalPreviousDistanceCar+previousJourneyList.get(i).getDistanceCar();	
						}
					   
					   for(int i = 0;i<previousJourneyList.size();i++){
						   totalPreviousDistanceBicycle = totalPreviousDistanceBicycle+previousJourneyList.get(i).getDistanceBicycle();	
						}
					   
					   for(int i = 0;i<previousJourneyList.size();i++){
						   totalPreviousDistanceBus = totalPreviousDistanceBus+previousJourneyList.get(i).getDistanceBus();	
						}
					   for(int i = 0;i<previousJourneyList.size();i++){
						   totalPreviousDistanceWalking = totalPreviousDistanceWalking+previousJourneyList.get(i).getDistanceWalking();	
						}
					   
					   for(int i = 0;i<previousJourneyList.size();i++){
						   totalPreviousDistanceFerry = totalPreviousDistanceFerry+previousJourneyList.get(i).getDistanceFerry();	
						}
					   for(int i = 0;i<previousJourneyList.size();i++){
						   totalPreviousDistanceTrain = totalPreviousDistanceTrain+previousJourneyList.get(i).getDistanceTrain();	
						}
					   for(int i = 0;i<previousJourneyList.size();i++){
						   totalPreviousDistanceAeroplane = totalPreviousDistanceAeroplane+previousJourneyList.get(i).getDistanceAeroplane();	
						}
						
//					   
					   int totalDistancePrevious = totalPreviousDistanceCar+
							   totalPreviousDistanceBicycle+
							   totalPreviousDistanceBus+
							   totalPreviousDistanceWalking+
							   totalPreviousDistanceFerry+
							   totalPreviousDistanceTrain+
							   totalPreviousDistanceAeroplane;
					   
					   
					   //previous segments
//					   
//					
				   
					   
					   
					   double bicycleDistPercentagePrev = Math.floor(((double)totalPreviousDistanceBicycle/totalDistancePrevious)*100);
					   int percentageBicycleKMPrev = (int)bicycleDistPercentagePrev;
					   		   
					   double carDistPercentagePrev = Math.floor(((double)totalPreviousDistanceCar/totalDistancePrevious)*100);
					   int percentageCarKMPrev = (int)carDistPercentagePrev;
					  
					   double walkingDistPercentagePrev = Math.floor(((double)totalPreviousDistanceWalking/totalDistancePrevious)*100);
					   int percentageWalkingKMPrev = (int)walkingDistPercentagePrev;
					   
					   double busDistPercentagePrev = Math.floor(((double)totalPreviousDistanceBus/totalDistancePrevious)*100);
					   int percentageBusKMPrev = (int)busDistPercentagePrev;
					   
					   double ferryDistPercentagePrev = Math.floor(((double)totalPreviousDistanceFerry/totalDistancePrevious)*100);
					   int percentageFerryKMPrev = (int)ferryDistPercentagePrev;
					   
					   double trainDistPercentagePrev = Math.floor(((double)totalPreviousDistanceTrain/totalDistancePrevious)*100);
					   int percentageTrainKMPrev = (int)trainDistPercentagePrev;
					   
					   double aeroplaneDistPercentagePrev = Math.floor(((double)totalPreviousDistanceAeroplane/totalDistancePrevious)*100);
					   int percentageAeroplaneKMPrev = (int)aeroplaneDistPercentagePrev;
					   
//					  
				   
				   for(int i = 0;i<respRideList.size();i++){
					   rideCategoryList.add(respRideList.get(i).getCategory());
					  
					   if(respRideList.get(i).getCategory()!=null && respRideList.get(i).getCategory().equalsIgnoreCase("Car")){
						   imgUrlCar = "images/co2CarM.png";
						   iconUrlCar ="images/red.png";	
						}
						if(respRideList.get(i).getCategory()!=null && respRideList.get(i).getCategory().equalsIgnoreCase("Bus")){
							imgUrlBus = "images/co2Bus.png";
							iconUrlBus ="images/black.png";
						}
						if(respRideList.get(i).getCategory()!=null && respRideList.get(i).getCategory().equalsIgnoreCase("Bicycle")){
							imgUrlBicycle = "images/co2Bicycle.png";
							iconUrlBicycle ="images/green.png";
						}
						if(respRideList.get(i).getCategory()!=null && respRideList.get(i).getCategory().equalsIgnoreCase("Walking")){
							imgUrlWalking = "images/co2Walking.png";
							iconUrlWalking ="images/purple.png";
							
						}
						if(respRideList.get(i).getCategory()!=null && respRideList.get(i).getCategory().equalsIgnoreCase("TRAIN_SUBWAY_METRO")){
							imgUrlTrain = "images/co2Train.png";
							iconUrlTrain ="images/pink.png";
							
						}
						if(respRideList.get(i).getCategory()!=null && respRideList.get(i).getCategory().equalsIgnoreCase("Ferry")){
							imgUrlFerry = "images/co2Ferry.png";
							iconUrlFerry ="images/blue.png";
							
						}
						if(respRideList.get(i).getCategory()!=null && respRideList.get(i).getCategory().equalsIgnoreCase("Aeroplane")){
							imgUrlAeroplane = "images/co2Aeroplane.png";
							iconUrlAeroplane ="images/silver.png";
							
						}
					}
				   
				   
				   // image for previous
				   
					//Previous image 
					
					String imgPreviousUrlCar = null;
					String iconPreviousUrlCar = null;
					String imgPreviousUrlBus = null;
					String iconPreviousUrlBus = null;
					String imgPreviousUrlBicycle = null;
					String iconPreviousUrlBicycle = null;
					String imgPreviousUrlWalking = null;
					String iconPreviousUrlWalking = null;
					String imgPreviousUrlTrain = null;
					String iconPreviousUrlTrain = null;
					String imgPreviousUrlFerry = null;
					String iconPreviousUrlFerry = null;
					String imgPreviousUrlAeroplane = null;
					String iconPreviousUrlAeroplane = null;
				   
				   for(int i = 0;i<previousJourneyList.size();i++){
					   //previousJourneyList.add(previousJourneyList.get(i).getCategory());
					  
					   if(previousJourneyList.get(i).getCategory()!=null && previousJourneyList.get(i).getCategory().equalsIgnoreCase("Car")){
						   imgPreviousUrlCar = "images/co2CarM.png";
						   iconPreviousUrlCar ="images/red.png";	
						}
						if(previousJourneyList.get(i).getCategory()!=null && previousJourneyList.get(i).getCategory().equalsIgnoreCase("Bus")){
							imgPreviousUrlBus = "images/co2Bus.png";
							iconPreviousUrlBus ="images/black.png";
						}
						if(previousJourneyList.get(i).getCategory()!=null && previousJourneyList.get(i).getCategory().equalsIgnoreCase("Bicycle")){
							imgPreviousUrlBicycle = "images/co2Bicycle.png";
							iconPreviousUrlBicycle ="images/green.png";
						}
						if(previousJourneyList.get(i).getCategory()!=null && previousJourneyList.get(i).getCategory().equalsIgnoreCase("Walking")){
							imgPreviousUrlWalking = "images/co2Walking.png";
							iconPreviousUrlWalking ="images/purple.png";
							
						}
						if(previousJourneyList.get(i).getCategory()!=null && previousJourneyList.get(i).getCategory().equalsIgnoreCase("TRAIN_SUBWAY_METRO")){
							imgPreviousUrlTrain = "images/co2Train.png";
							iconPreviousUrlTrain ="images/pink.png";
							
						}
						if(previousJourneyList.get(i).getCategory()!=null && previousJourneyList.get(i).getCategory().equalsIgnoreCase("Ferry")){
							imgPreviousUrlFerry = "images/co2Ferry.png";
							iconPreviousUrlFerry ="images/blue.png";
							
						}
						if(previousJourneyList.get(i).getCategory()!=null && previousJourneyList.get(i).getCategory().equalsIgnoreCase("Aeroplane")){
							imgPreviousUrlAeroplane = "images/co2Aeroplane.png";
							iconPreviousUrlAeroplane ="images/silver.png";
							
						}
					}
				   
				   
				   
				   
				   for(int i = 0;i<respRideList.size();i++){
					   
					   if(respRideList.get(i).getCategory()!=null){
					   
					       latLongList.add(Double.toString(respRideList.get(i).getStartAddressGpslat()));
						   latLongList.add(Double.toString(respRideList.get(i).getStartAddressGpslng()));
					      latLongList.add(respRideList.get(i).getCategory());
					       
					   }
						   
					   }
					 	   
					   for(int i = 0;i<respRideList.size();i++){
						   if(respRideList.get(i).getCategory()!=null){
							  
						   latLongDest.add(Double.toString(respRideList.get(i).getEndAddressGpslat()));
						   latLongDest.add(Double.toString(respRideList.get(i).getEndAddressGpslng()));
						   latLongDest.add("DESTINATION");
						   }
					   }
					   
					   latLongList.addAll(latLongDest);//merging the two Arraylists of segments and destinations
					   
					  
				   String pathNew = getServletContext().getRealPath("/js/");  
					log.debug("Path for xml: " + pathNew);
				    
					CGUtilClass utilObj = new CGUtilClass();
					utilObj.WriteXml(latLongList,pathNew,"\\compareLocation.xml");
					
					
					//Previous data xml ......donno if only read of xml is enough or not!!!!
					ArrayList<String> previousStartList = new ArrayList<String>();
					ArrayList<String> previousDestList = new ArrayList<String>();
					
					   for(int i = 0;i<previousJourneyList.size();i++){
						   
						   if(previousJourneyList.get(i).getCategory()!=null){
						   
							   previousStartList.add(Double.toString(previousJourneyList.get(i).getStartAddressGpslat()));
							   previousStartList.add(Double.toString(previousJourneyList.get(i).getStartAddressGpslng()));
							   previousStartList.add(previousJourneyList.get(i).getCategory());
						       
						   }
							   
						   }
						 	   
						   for(int i = 0;i<previousJourneyList.size();i++){
							   if(previousJourneyList.get(i).getCategory()!=null){
								  
								   previousDestList.add(Double.toString(previousJourneyList.get(i).getEndAddressGpslat()));
								   previousDestList.add(Double.toString(previousJourneyList.get(i).getEndAddressGpslng()));
								   previousDestList.add("DESTINATION");
							   }
						   }
						   
						   previousStartList.addAll(previousDestList);//merging the two Arraylists of segments and destinations
						   
						  
					   String pathPrevious = getServletContext().getRealPath("/js/");  
						log.debug("Path for xml: " + pathNew);
					    
						//CGUtilClass utilObj = new CGUtilClass();
						
						// Code for writing previous xml again
						//utilObj.WriteXml(latLongList,pathPrevious,"\\startLocation.xml");
				    
				    
					request.setAttribute("totalCo2Car", totalCo2Car);
					request.setAttribute("totalCo2Bus", totalCo2Bus);
					request.setAttribute("totalCo2Walking", totalCo2Walking);
					request.setAttribute("totalCo2Bicycle", totalCo2Bicycle);
					request.setAttribute("totalCo2Train", totalCo2Train);
					request.setAttribute("totalCo2Ferry", totalCo2Ferry);
					request.setAttribute("totalCo2Aeroplane", totalCo2Aeroplane);
					request.setAttribute("imgUrlCar",imgUrlCar);
					request.setAttribute("iconUrlCar",iconUrlCar);
					request.setAttribute("imgUrlBus",imgUrlBus);
					request.setAttribute("iconUrlBus",iconUrlBus);
					request.setAttribute("imgUrlBicycle",imgUrlBicycle);
					request.setAttribute("iconUrlBicycle",iconUrlBicycle);
					request.setAttribute("imgUrlWalking",imgUrlWalking);
					request.setAttribute("iconUrlWalking",iconUrlWalking);
					request.setAttribute("imgUrlTrain",imgUrlTrain);
					request.setAttribute("iconUrlTrain",iconUrlTrain);
					request.setAttribute("imgUrlFerry",imgUrlFerry);
					request.setAttribute("iconUrlFerry",iconUrlFerry);
					request.setAttribute("imgUrlAeroplane",imgUrlAeroplane);
					request.setAttribute("iconUrlAeroplane",iconUrlAeroplane);
					request.setAttribute("totalCo2", totalCo2);
					request.setAttribute("ride",ride);
					request.setAttribute("rideList", respRideList);
					request.setAttribute("totalDistanceCar",totalDistanceCar);
					request.setAttribute("totalDistanceBus",totalDistanceBus);
					request.setAttribute("totalDistanceBicycle",totalDistanceBicycle);
					request.setAttribute("totalDistanceWalking",totalDistanceWalking);
					request.setAttribute("totalDistanceFerry",totalDistanceFerry);
					request.setAttribute("totalDistanceAeroplane",totalDistanceAeroplane);
					request.setAttribute("totalDistanceTrain",totalDistanceTrain);
					
					
					request.setAttribute("percentageCarKM", percentageCarKM);
					request.setAttribute("percentageBicycleKM", percentageBicycleKM);
					request.setAttribute("percentageWalkingKM", percentageWalkingKM);
					request.setAttribute("percentageBusKM", percentageBusKM);
					request.setAttribute("percentageFerryKM", percentageFerryKM);
					request.setAttribute("percentageAeroplaneKM", percentageAeroplaneKM);
					request.setAttribute("percentageTrainKM", percentageTrainKM);
					request.setAttribute("totalDistance", totalDistance);
					String destination = "/jsp/CompareCommutingPeriod.jsp";
					
					
					
					//setting previous parameters in req
				
					request.setAttribute("totalPreviousCo2Car", totalPreviousCo2Car);
					request.setAttribute("totalPreviousCo2Bus", totalPreviousCo2Bus);
					request.setAttribute("totalPreviousCo2Walking", totalPreviousCo2Walking);
					request.setAttribute("totalPreviousCo2Bicycle", totalPreviousCo2Bicycle);
					request.setAttribute("totalPreviousCo2Train", totalPreviousCo2Train);
					request.setAttribute("totalPreviousCo2Ferry", totalPreviousCo2Ferry);
					request.setAttribute("totalPreviousCo2Aeroplane", totalPreviousCo2Aeroplane);
					
					
					
					request.setAttribute("imgPreviousUrlCar",imgPreviousUrlCar);
					request.setAttribute("iconPreviousUrlCar",iconPreviousUrlCar);
					request.setAttribute("imgPreviousUrlBus",imgPreviousUrlBus);
					request.setAttribute("iconPreviousUrlBus",iconPreviousUrlBus);
					request.setAttribute("imgPreviousUrlBicycle",imgPreviousUrlBicycle);
					request.setAttribute("iconPreviousUrlBicycle",iconPreviousUrlBicycle);
					request.setAttribute("imgPreviousUrlWalking",imgPreviousUrlWalking);
					request.setAttribute("iconPreviousUrlWalking",iconPreviousUrlWalking);
					request.setAttribute("imgPreviousUrlTrain",imgPreviousUrlTrain);
					request.setAttribute("iconPreviousUrlTrain",iconPreviousUrlTrain);
					request.setAttribute("imgPreviousUrlFerry",imgPreviousUrlFerry);
					request.setAttribute("iconPreviousUrlFerry",iconPreviousUrlFerry);
					request.setAttribute("imgPreviousUrlAeroplane",imgPreviousUrlAeroplane);
					request.setAttribute("iconPreviousUrlAeroplane",iconPreviousUrlAeroplane);
					
					
					
					request.setAttribute("totalPreviousDistanceCar",totalPreviousDistanceCar);
					request.setAttribute("totalPreviousDistanceBicycle",totalPreviousDistanceBicycle);
					request.setAttribute("totalPreviousDistanceBus",totalPreviousDistanceBus);
					request.setAttribute("totalPreviousDistanceWalking",totalPreviousDistanceWalking);
					request.setAttribute("totalPreviousDistanceFerry",totalPreviousDistanceFerry);
					request.setAttribute("totalPreviousDistanceTrain",totalPreviousDistanceTrain);
					request.setAttribute("totalPreviousDistanceAeroplane",totalPreviousDistanceAeroplane);
					
					
					 
					
					request.setAttribute("percentageBicycleKMPrev", percentageBicycleKMPrev);
					 request.setAttribute("percentageCarKMPrev", percentageCarKMPrev);
					 request.setAttribute("percentageWalkingKMPrev", percentageWalkingKMPrev);
					 request.setAttribute("percentageBusKMPrev", percentageBusKMPrev);
					 request.setAttribute("percentageFerryKMPrev", percentageFerryKMPrev);
					 request.setAttribute("percentageTrainKMPrev", percentageTrainKMPrev);
					 request.setAttribute("percentageAeroplaneKMPrev", percentageAeroplaneKMPrev);
					 
				
					
					request.setAttribute("totalCo2Previous", totalCo2Previous);
					//request.setAttribute("totalDistancePrevious", totalDistancePrevious);
					
					RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
					rd.forward(request, response);
				
				} catch (NumberFormatException e) {
					log.error("Error in parsing the request");
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					e.printStackTrace(new PrintStream(out,true));
					log.error(out.toString().replaceAll("\t", " "));
					sendtErrResp(response, "Error: Error in parsing the request's parameters", HttpServletResponse.SC_BAD_REQUEST);
				} catch (Exception e) {
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					e.printStackTrace(new PrintStream(out,true));
					log.error(out.toString().replaceAll("\t", " "));
					sendtErrResp(response, "Internal server Error", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				}
			} else {
				StringBuffer sb = new StringBuffer();
				sb.append("?");
				Enumeration<String> params = request.getParameterNames();
				while(params.hasMoreElements()){
					String par = params.nextElement();
					sb.append(par);
					sb.append("=");
					sb.append(request.getParameter(par));
					sb.append("&");
				}
				sb.deleteCharAt(sb.length()-1);	
				log.warn("Missing parameters in the request: " + request.getRequestURL() + sb.toString());
		        sendtErrResp(response, "Error: All the parameters are obligatory", HttpServletResponse.SC_BAD_REQUEST);
			}
			       
				       
}
private void sendtErrResp(HttpServletResponse response, String errMsg, int errType) throws IOException{
				StringBuffer sb = new StringBuffer();
				// TODO hardcoded, to put in the configuration file.
				sb.append("<html>");
			    sb.append("<head><title>Error</title></title>");
			    sb.append("<body>");
			    sb.append("<h1>"+ errMsg +"</h1>");
			    sb.append("</body></html>");
				byte[] outputData = sb.toString().getBytes();
		        response.setContentLength(outputData.length);
		        OutputStream httpOutputStream = response.getOutputStream();
		        try {
		        	response.setStatus(errType);
		            httpOutputStream.write(outputData);
		        } finally {
		            httpOutputStream.close();
		        }
			}
}